<template>
  <div class="product-info">
    <h1 class="page-title">产品信息管理</h1>
    
    <!-- 搜索区域 -->
    <div class="filter-bar">
      <el-input
        v-model="filterForm.productName"
        placeholder="请输入产品ID（支持模糊查询）"
        clearable
        style="width: 200px; margin-right: 10px;"
        @keyup.enter="handleSearch"
        @clear="handleSearch"
      />
      <el-select
        v-model="filterForm.status"
        placeholder="请选择状态"
        clearable
        style="width: 150px; margin-right: 10px;"
        @clear="handleSearch"
      >
        <el-option label="在售" value="1"></el-option>
        <el-option label="下架" value="0"></el-option>
      </el-select>
      <el-button type="primary" @click="handleSearch" icon="el-icon-search">查询</el-button>
      <el-button @click="resetFilter" icon="el-icon-refresh" style="margin-left: 10px;">重置</el-button>
      <el-button type="success" @click="handleAdd" icon="el-icon-plus" style="margin-left: 10px;">新增</el-button>
    </div>
    
    <!-- 表格区域 -->
    <div class="table-container">
      <el-table :data="productList" style="width: 100%" border v-loading="loading">
        <el-table-column prop="id" label="产品ID" width="110" />
        <el-table-column prop="productName" label="产品名称" width="100" />
        <el-table-column prop="categoryName" label="产品类型" width="120">
          <template #default="scope">
            {{ scope.row.categoryName || '未关联类型' }}
          </template>
        </el-table-column>
        <el-table-column prop="supplierName" label="供应商" width="150">
          <template #default="scope">
            {{ scope.row.supplierName || '未关联供应商' }}
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="100" />
        <el-table-column prop="stock" label="库存" width="90" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleEdit(scope.row)"
            >
              修改
            </el-button>
            <el-button
              size="small"
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="toggleStatus(scope.row)"
              :disabled="scope.row.status === 2"
            >
              {{ scope.row.status === 1 ? '下架' : '上架' }}
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteProduct(scope.row)"
              :disabled="scope.row.status === 2"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <el-pagination
        @size-change="handlePageSizeChange"
        @current-change="handlePageChange"
        :current-page="pagination.pageNo"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        style="margin-top: 20px;"
      />
    </div>
    
    <!-- 新增/修改弹窗 -->
    <el-dialog
      :title="form.id ? '修改产品信息' : '新增产品信息'"
      v-model="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="form"
        ref="form"
        label-width="100px"
        :rules="rules"
      >
        <!-- 1. 产品名称 -->
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称" />
        </el-form-item>

        <!-- 2. 供应商下拉 -->
        <el-form-item label="供应商" prop="supplierId">
          <el-select
            v-model="form.supplierId"
            placeholder="请选择供应商"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="supplier in supplierList"
              :key="supplier.id"
              :label="supplier.supplierName"
              :value="supplier.id"
            />
          </el-select>
        </el-form-item>

        <!-- 3. 产品类别下拉（新增/改造部分） -->
        <el-form-item label="产品类别" prop="categoryId">
          <el-select
            v-model="form.categoryId"
            placeholder="请选择产品类别"
            clearable
            filterable
            style="width: 100%"
          >
            <!-- 下拉选项：value=类别ID（关联产品表），label=类别名称（显示文本） -->
            <el-option
              v-for="category in categoryList"
              :key="category.id"
              :label="category.categoryName"
              :value="category.id"
            >
              <!-- 可选：显示类别状态（如"启用"/"禁用"），增强用户感知 -->
              <span>{{ category.categoryName }}</span>
              <span class="category-status" :class="category.status === 1 ? 'status-enabled' : 'status-disabled'">
                {{ category.status === 1 ? '（启用）' : '（禁用）' }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="库存" prop="stock">
          <el-input v-model.number="form.stock" type="number"></el-input>
        </el-form-item>
        <!-- 只在修改时显示状态选项 -->
        <el-form-item label="状态" v-if="form.id">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">在售</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { 
  getProductListAPI, 
  getProductByIdAPI, 
  getProductByNameExactAPI, 
  updateProductStatusAPI, 
  deleteProductAPI, 
  addProductAPI, 
  updateProductAPI,
  getAllValidSuppliersAPI,
  getAllValidProductCategoriesAPI
} from '@/apis/supplier'

export default {
  name: 'SupplierProductInfo',
  data() {
    return {
      // 弹窗相关
      dialogVisible: false,
      form: {
        id: null,
        productName: '',
        supplierId: null,
        categoryId: null,
        stock: null,
        status: 1,
        revision: 1
      },
      rules: {
        productName: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
        supplierId: [{ required: true, message: '请选择供应商', trigger: 'change' }],
        categoryId: [{ required: true, message: '请选择产品类别', trigger: 'change' }],
        stock: [{ required: true, message: '请输入库存数量', trigger: 'blur' }]
      },
      // 列表数据
      productList: [],
      pagination: {
        pageNo: 1,
        pageSize: 10,
        total: 0
      },
      loading: false,
      // 搜索表单
      filterForm: {
        productName: '',
        status: ''
      },
      // 新增：产品类别下拉数据源（存储{id, categoryName, status...}）
      categoryList: [],
      // 新增：类别加载状态（避免未加载完时用户操作）
      categoryLoading: false,
      // 新增：供应商下拉数据源（存储{id, supplierName, phone...}）
      supplierList: [],
      // 新增：加载状态（避免下拉数据未加载完时用户操作）
      supplierLoading: false
    }
  },
  created() {
    this.fetchProductList()
    this.fetchValidSuppliers()
    this.fetchValidProductCategories()
  },
  methods: {
    // 查询方法 - 智能判断是ID查询还是名称查询
    handleSearch() {
      this.pagination.pageNo = 1
      // 如果有输入内容，判断是ID查询还是名称查询
      if (this.filterForm.productName && this.filterForm.productName.trim()) {
        const keyword = this.filterForm.productName.trim();
        
        // 如果输入的是纯数字，优先按ID精确查询
        if (/^\d+$/.test(keyword)) {
          this.searchById(parseInt(keyword));
        } else {
          // 否则按名称精确查询
          this.searchByNameExact();
        }
      } else {
        // 如果没有输入内容，获取所有产品
        this.fetchProductList();
      }
    },

    // 重置筛选
    resetFilter() {
      this.filterForm = {
        productName: '',
        status: ''
      }
      this.handleSearch()
    },

    // 获取列表数据（通用查询）
    async fetchProductList() {
      this.loading = true
      try {
        // 构造正确的请求参数格式
        const params = {
          pageNo: this.pagination.pageNo,
          pageSize: this.pagination.pageSize
        };
        
        // 构造搜索条件对象
        const bo = {};
        
        // 处理产品名称搜索条件
        if (this.filterForm.productName && this.filterForm.productName.trim() !== '') {
          const keyword = this.filterForm.productName.trim();
          // 如果是纯数字，按ID查询
          if (/^\d+$/.test(keyword)) {
            if (keyword.length <= 8) {
              bo.id = parseInt(keyword);
            } else {
              // 10位数字按名称查询
              bo.productName = keyword;
            }
          } else {
            // 非数字按名称模糊查询
            bo.keyword = keyword;
          }
        }
        
        // 处理状态搜索条件
        if (this.filterForm.status !== '' && this.filterForm.status !== undefined) {
          bo.status = parseInt(this.filterForm.status);
        }
        
        // 只有当有搜索条件时才添加bo对象
        if (Object.keys(bo).length > 0) {
          params.bo = bo;
        }
        
        console.log('准备发送产品列表请求，完整参数:', JSON.stringify(params, null, 2));
        
        const res = await getProductListAPI(params)
        
        if (res.code === 0) {
          this.productList = res.data?.records || []
          this.pagination.total = res.data?.total || 0
          console.log(`成功获取产品列表，共${this.pagination.total}条记录，当前页显示${this.productList.length}条`);
        } else {
          throw new Error(res.msg || '获取数据失败')
        }
        
        console.log('产品列表响应:', res);
      } catch (error) {
        console.error('获取产品列表失败:', error)
        this.$message.error(error.data?.msg || error.message || '获取产品列表失败')
        this.productList = []
      } finally {
        this.loading = false
      }
    },

    // 通过ID精确查找的方法
    async searchById(id) {
      try {
        this.loading = true;
        const res = await getProductByIdAPI(id);
        
        if (res.data) {
          // 将单个结果转换为列表格式以适配现有表格
          this.productList = [res.data];
          this.pagination.total = 1;
          this.$message.success('查找成功');
        } else {
          this.productList = [];
          this.pagination.total = 0;
          this.$message.warning('未找到指定ID的产品');
        }
      } catch (error) {
        console.error('获取产品信息失败:', error);
        this.$message.error(error.data?.msg || '获取产品信息失败');
        this.productList = [];
        this.pagination.total = 0;
      } finally {
        this.loading = false;
      }
    },

    // 通过产品名称精确查找的方法
    async searchByNameExact() {
      try {
        this.loading = true;
        const name = this.filterForm.productName.trim();
        const res = await getProductByNameExactAPI(name);
        
        if (res.data && res.data.records) {
          this.productList = res.data.records;
          this.pagination.total = res.data.total;
          
          if (res.data.records.length > 0) {
            this.$message.success(`找到 ${res.data.records.length} 个匹配的产品`);
          } else {
            this.$message.warning('未找到匹配的产品');
          }
        } else {
          this.productList = [];
          this.pagination.total = 0;
          this.$message.warning('未找到匹配的产品');
        }
      } catch (error) {
        console.error('获取产品信息失败:', error);
        this.$message.error(error.data?.msg || '获取产品信息失败');
        this.productList = [];
        this.pagination.total = 0;
      } finally {
        this.loading = false;
      }
    },

    // 新增：加载所有有效供应商（下拉数据源）
    async fetchValidSuppliers() {
      this.supplierLoading = true;
      try {
        const res = await getAllValidSuppliersAPI();
        // 从分页结果中提取供应商列表（records字段存储分页数据）
        this.supplierList = res.data?.records || [];
        console.log(`加载有效供应商数量：${this.supplierList.length}`);
      } catch (error) {
        console.error('加载供应商下拉数据失败:', error);
        this.$message.error('加载供应商列表失败，请刷新页面重试');
        this.supplierList = [];
      } finally {
        this.supplierLoading = false;
      }
    },

    // 新增：加载所有有效产品类别（下拉数据源）
    async fetchValidProductCategories() {
      this.categoryLoading = true;
      try {
        const res = await getAllValidProductCategoriesAPI();
        // 从分页结果的records字段提取类别列表
        this.categoryList = res.data?.records || [];
        console.log(`加载有效产品类别数量：${this.categoryList.length}`);
      } catch (error) {
        console.error('加载产品类别下拉数据失败:', error);
        this.$message.error('加载产品类别列表失败，请刷新页面重试');
        this.categoryList = [];
      } finally {
        this.categoryLoading = false;
      }
    },

    // 新增产品
    handleAdd() {
      this.form = {
        id: null,
        productName: '',
        supplierId: null,
        categoryId: null,
        stock: null,
        status: 1,
        revision: 1
      }
      this.dialogVisible = true
    },

    // 打开修改弹窗
    handleEdit(row) {
      // 深拷贝行数据，避免直接修改表格数据
      this.form = { ...row }
      this.dialogVisible = true
    },

    // 提交表单（新增或修改）
    async submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            this.loading = true
            if (this.form.id) {
              // 修改产品
              const updateData = {
                id: this.form.id,
                productName: this.form.productName,
                supplierId: this.form.supplierId,
                categoryId: this.form.categoryId,
                stock: this.form.stock,
                status: this.form.status,
                revision: this.form.revision
              }
              await updateProductAPI(updateData)
              this.$message.success('修改成功')
            } else {
              // 新增产品 - 确保 status 和 revision 有默认值
              const addData = {
                productName: this.form.productName,
                supplierId: this.form.supplierId,
                categoryId: this.form.categoryId,
                stock: this.form.stock,
                status: this.form.status || 1,
                revision: this.form.revision || 1
              }
              await addProductAPI(addData)
              this.$message.success('新增成功')
            }
            this.dialogVisible = false
            await this.handleSearch() // 重新加载数据确保同步
          } catch (error) {
            console.error('操作失败:', error)
            this.$message.error(error.data?.msg || '操作失败')
          } finally {
            this.loading = false
          }
        }
      })
    },

    // 分页处理
    handlePageChange(pageNo) {
      this.pagination.pageNo = pageNo
      this.fetchProductList()
    },

    handlePageSizeChange(pageSize) {
      this.pagination.pageSize = pageSize
      this.pagination.pageNo = 1
      this.fetchProductList()
    },

    // 时间格式化
    formatDateTime(date) {
      if (!date) return ''
      const d = new Date(date)
      if (isNaN(d.getTime())) return date
      
      return `${d.getFullYear()}-${this.padZero(d.getMonth() + 1)}-${this.padZero(d.getDate())} ${this.padZero(d.getHours())}:${this.padZero(d.getMinutes())}:${this.padZero(d.getSeconds())}`
    },

    padZero(num) {
      return num < 10 ? `0${num}` : num
    },

    // 状态样式
    getStatusType(status) {
      switch (status) {
        case 0: return 'warning'
        case 1: return 'success'
        case 2: return 'danger'
        default: return 'info'
      }
    },

    // 状态文本
    getStatusText(status) {
      switch (status) {
        case 0: return '下架'
        case 1: return '在售'
        case 2: return '已删除'
        default: return '未知'
      }
    },

    // 切换状态
    async toggleStatus(row) {
      if (this.loading) return
      try {
        const newStatus = row.status === 1 ? 0 : 1
        this.loading = true
        await updateProductStatusAPI({ id: row.id, status: newStatus })
        row.status = newStatus
        row.updateTime = new Date().toISOString()
        this.$message.success(`${newStatus === 1 ? '上架' : '下架'}成功`)
      } catch (error) {
        console.error('更新状态失败:', error)
        this.$message.error(error.data?.msg || '更新状态失败')
      } finally {
        this.loading = false
      }
    },

    // 删除产品
    async deleteProduct(row) {
      if (row.status === 2) {
        this.$message.warning('该产品已处于删除状态')
        return
      }

      this.$confirm('此操作将删除该产品，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        if (this.loading) return
        try {
          this.loading = true
          await deleteProductAPI(row.id)
          // 2. 关键修改：重新请求列表，利用后端逻辑过滤已删除数据
          await this.handleSearch()
          row.status = 2
          row.updateTime = new Date().toISOString()
          this.$message.success('删除成功!')
        } catch (error) {
          console.error('删除失败:', error)
          this.$message.error(error.data?.msg || '删除失败')
        } finally {
          this.loading = false
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  }
}
</script>

<style scoped>
.product-info {
  padding: 20px;
  background-color: #f5f5f5;
  text-align: center;
}

.page-title {
  font-size: 2.2rem;
  color: #2c3e50;
  margin: 20px 0;
  text-align: center;
  font-weight: bold;
}

.filter-bar {
  background-color: white;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.table-container {
  margin-top: 20px;
  background-color: white;
  padding: 20px;
  border-radius: 4px;
  text-align: left;
}

@media (max-width: 768px) {
  .page-title {
    font-size: 1.8rem;
  }
  
  .filter-bar {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>